<template>
  <fks-dialog
    :append-to-body="true"
    :visible.sync="detailDialogVisible"
    width="480px"
    destroy-on-close
    @close="close"
    @open="openDialog"
  >
    <div slot="title">
      <i
        v-if="title == LANG.ADD"
        class="fks-icon-plus"
      />
      <i
        v-if="title == LANG.EDIT"
        class="fks-icon-edit"
      />
      {{ title }}
    </div>
    <fks-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="90px"
    >
      <fks-form-item
        :span="24"
        lead
        :label="LANG.DICCODE"
        prop="code"
      >
        <fks-input
          v-model="form.code"
          maxlength="50"
          show-word-limit
        />
      </fks-form-item>
      <fks-form-item
        :span="24"
        :label="LANG.SUPDIC"
        prop="parentId"
      >
        <fks-select
          v-model="form.dictionaryId"
          clearable
          disabled
          style="width: 100%"
          placeholder="请选择所属字典"
          filterable
        >
          <fks-option
            v-for="item in tableData"
            :key="item.id"
            :label="item.content"
            :value="item.id"
          />
        </fks-select>
      </fks-form-item>
      <fks-form-item
        :span="24"
        lead
        :label="LANG.SORT"
        prop="sort"
      >
        <fks-input
          v-model.number="form.sort"
          maxlength="9"
          oninput="value=value.replace(/[^0-9.]/g,'')"
        />
      </fks-form-item>
      <fks-form-item
        v-for="item in arr"
        :key="item.key"
        :span="24"
        :label="item.label"
        :prop="item.key"
      >
        <fks-input
          v-model="form[item.key]"
          maxlength="255"
          show-word-limit
        />
      </fks-form-item>
      <fks-form-item
        v-if="showButton"
        :span="24"
        label
        prop
      >
        <fks-button
          v-if="!show"
          label
          style="width: 100%"
          icon="fks-icon-arrow-down"
          @click="showAll"
        >
          {{ LANG.ALL_LANGUAGES }}
        </fks-button>
        <fks-button
          v-if="show"
          label
          style="width: 100%"
          icon="fks-icon-arrow-up"
          @click="showNone"
        >
          {{ LANG.HIDE_LANGUAGES }}
        </fks-button>
      </fks-form-item>
    </fks-form>
    <template slot="footer">
      <fks-button
        type="primary"
        :loading="detailLoading"
        icon="fks-icon-check"
        @click="submitdetail"
      >
        <span style="margin-left: 4px">{{ LANG.SAVE }}</span>
      </fks-button>
    </template>
  </fks-dialog>
</template>

<script>
import { ENUM } from '@/store/State/stateTypes'
import { addEditDicDetail, getDic } from '@/modules/SysConfig/Dictionary/api'
import { lang } from '@/modules/SysConfig/Lang/langClass.js'

export default {
  name: 'DragTable',
  props: {
    data: {
      default() {
        return {
          code: ''
        }
      }
    },
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'add'
    }
  },
  data() {
    return {
      form: {},
      showButton: false,
      pId: [],
      defaultLabel: '',
      detailLoading: false,
      copyForm: {},
      detailDialogVisible: false,
      show: false,
      arr: [
        { label: '简体中文', key: 'zh-CN' },
        { label: 'English', key: 'en' }
      ],
      tableData: [],
      total: 0
    }
  },
  computed: {
    title() {
      switch (this.type) {
        case 'add':
          return this.LANG.ADD

        default:
          return this.LANG.EDIT
      }
    },
    languages() {
      return this.$store.state[ENUM].languages || []
    },
    rules() {
      return {
        code: [
          {
            required: true,
            message: this.LANG.DIC_KEY_NOT_EMPTY,
            trigger: 'blur'
          }
        ],
        parentId: [
          {
            required: true,
            message: this.LANG.DIC_DETAIL_DIC_NOT_EMPTY,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    data(val) {
      this.form = Object.assign({}, val)
      // this.pId = val.pId
      // this.total = val.detailTotal
      // if (this.type == 'add') {
      //   this.$set(this.form, val.parentId, val.id)
      // }
    },
    visible(val) {
      this.detailDialogVisible = val
    }
  },
  methods: {
    //不显示除中英外其他语种
    showNone() {
      this.arr = [
        { label: '简体中文', key: 'zh-CN' },
        { label: 'English', key: 'en' }
      ]
      this.show = false
    },
    //显示系统配置的所有语种
    showAll() {
      this.show = true
      this.languages.forEach((item) => {
        if (item.code != 'en' && item.code != 'zh-CN') {
          this.arr.push({ label: item.name, key: item.code })
        }
      })
    },
    //打开弹窗时的回调
    openDialog() {
      lang.forEach((item) => {
        if (item.code === this.$lang) {
          this.defaultLabel = item.name
        }
      })
      if (this.languages.length > 0) {
        this.languages.forEach((item) => {
          if (item.code != 'en' && item.code != 'zh-CN') {
            this.showButton = true
          }
        })
      } else {
        lang.forEach((item) => {
          if (item.code == this.$lang) {
            this.arr = [
              {
                label: item.name,
                key: this.$lang
              }
            ]
          }
        })
      }
      this.getDictData()
    },
    //获取所有字典数据
    getDictData() {
      const data = {
        page: 1,
        size: 99999,
        langCode: this.data.langCode || this.$lang,
        code: ''
      }
      getDic(data)
        .then((res) => {
          if (res.status) {
            this.tableData = res.data ? res.data.list : []
          }
        })
        .catch(() => {
          this.tableData = []
        })
    },
    //关闭弹窗时回调
    close() {
      this.$refs.form.clearValidate()
      this.form = {}
      this.$emit('update:visible', false)
      this.arr = [
        { label: '简体中文', key: 'zh-CN' },
        { label: 'English', key: 'en' }
      ]
      this.show = false
    },
    ifLang(key) {
      let w = false
      lang.forEach((item) => {
        if (item.code == key) {
          w = true
        }
      })
      return w
    },
    //新增字典详情数据保存方法
    addDicDetail() {
      this.copyForm = JSON.parse(JSON.stringify(this.form))
      let copyFormId = this.copyForm.id //暂存id，后面编辑时用到
      let tmp = {
        code: this.copyForm.code,
        sort: this.copyForm.sort,
        parentId:
          this.type == 'add'
            ? this.copyForm.parentId
            : this.copyForm.content.parentId,
        pathId:
          this.type == 'add'
            ? this.copyForm.pathId
            : this.copyForm.content.pathId
      }
      let params = []
      //删除copyForm的id属性，避免ifLang方法中key和code重复（id会重复）
      delete this.copyForm.id
      for (var key in this.copyForm) {
        if (this.ifLang(key)) {
          params.push({ content: this.copyForm[key], langCode: key })
        }
      }
      if (params.length > 0) {
        // if (this.type == 'add') {
        params.forEach((item) => {
          // Object.assign(item, tmp, { sort: this.total })
          Object.assign(item, tmp, { serviceType: 0, id: copyFormId })
        })
        // }
        // else {
        //   params.forEach((item) => {
        //     this.pId.forEach((value) => {
        //       if (item.langCode == value.label) {
        //         Object.assign(item, tmp, {
        //           id: value.id ? value.id : ''
        //         })
        //         return
        //       }
        //     })
        //   })
        // }

        this.addDicDetailList(params)
      } else {
        this.detailLoading = false
        this.$message.error(this.LANG.DETAIL_EMPTY)
      }
    },
    //新增 && 编辑字典详情数据
    addDicDetailList(params) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          //新增编辑走同一个接口，只是post 和 put区别
          addEditDicDetail(JSON.stringify(params), this.type)
            .then((res) => {
              this.detailLoading = false
              if (res.status) {
                if (this.title == this.LANG.ADD) {
                  this.$message.success(this.LANG.ADD_SUCCESS)
                } else {
                  this.$message.success(this.LANG.EDIT_SUCCESS)
                }
                this.close()
                this.$parent.updateDicDetail()
              }
            })
            .catch(() => {
              this.detailLoading = false
            })
        } else {
          this.detailLoading = false
        }
      })
    },
    submitdetail() {
      this.detailLoading = true
      this.addDicDetail()
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .fks-dialog__body {
  padding-bottom: 0;
}
</style>
